package IBBB.view;

import IBBB.model.UserMessage;
import IBBB.model.WordStockMessage;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.MapChangeListener;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.text.Font;
import javafx.scene.text.Text;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class PersonalMessagePane {
    @FXML
    private FlowPane containers;
    @FXML
    private Text userName;
    private UserMessage userMessage;
    private WordStockMessage wordStockMessage;
    ObservableMap<StringProperty, List<IntegerProperty>> schedules;

    public void init(UserMessage userMessage, WordStockMessage wordStockMessage) throws IOException {
        this.userMessage = userMessage;
        this.wordStockMessage = wordStockMessage;
        schedules = userMessage.getWordStockInfo();
        userName.setText(userMessage.getUserName().getValue());
        userName.textProperty().bind(userMessage.getUserName());
        schedules.addListener((MapChangeListener<StringProperty, List<IntegerProperty>>) change -> {
            if (change.wasRemoved() || change.wasAdded()) {
                try {
                    initSchedule();
                } catch (IOException e) {
                    //TODO: handle error
                    e.printStackTrace();
                }
            }
        });
        initSchedule();
    }

    private void initSchedule() throws IOException {
        containers.getChildren().clear();
        if (schedules.entrySet().size() == 0) {
            Label label = new Label();
            label.setText("\n\n\n      还没有计划，快去新建一个吧~");
            label.setFont(new Font(25));
            containers.getChildren().add(label);
        }
        Map<String, Integer> wordStocks = wordStockMessage.getMessage();
        for (Map.Entry<StringProperty, List<IntegerProperty>> item: schedules.entrySet()) {
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(getClass().getResource("PersonalScheduleBox.fxml"));
            Parent node = loader.load();
            PersonalScheduleBox controller = loader.getController();
            controller.init(userMessage, item.getKey(), item.getValue().get(0), wordStocks.get(item.getKey().get()), item.getValue().get(1));
            containers.getChildren().add(node);
        }
    }
}
